<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name$lk" placeholder="角色名称" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >
        查询
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleAdd"
        >
        添加角色
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="handlePlDelete"
        >
        批量删除
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="角色名称" prop="name" align="center" />
      <el-table-column label="备注" prop="remark" align="center" />
      <!-- <el-table-column label="状态" prop="statusText" align="center" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleEdit(row)">
            编辑角色
          </el-button>
          <el-button type="success" size="mini" @click="handleRoleAuth(row.id)">
            编辑角色权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-tree
        ref="tree"
        :data="menuList"
        show-checkbox
        node-key="id"
        :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="addDialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="addFormData" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="addFormData.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveAddRoleData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { rolePageByQo, roleRemoveByIds, getRoleMenus, editRoleMenus, roleSave } from '@/api/system'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Driver',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name$lk: ''
      },
      multipleSelection: [],
      dialogFormVisible: false,
      menuList: [],
      defaultProps: {
        children: 'children',
        label: (data, node) => {
          return this.getTreeLabel(data, node)
        }
      },
      roleId: '',
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      addFormData: {
        name: '',
        status: 1,
        remark: ''
      },
      addDialogFormVisible: false,
      title: '添加',
      type: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      rolePageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    toSave(id) {
      this.$router.push({ path: `/system/role/save`, query: { id: id } })
    },
    // 批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val.map((ele) => {
        return ele.id
      })
    },
    handlePlDelete() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      
      this.$confirm('是否继续删除？').then(() => {
        roleRemoveByIds(params).then(() => {
          this.$notify({
            title: '成功',
            message: '批量删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleAdd() {
      this.addDialogFormVisible = true
      this.title = '添加'
      this.type = false
    },
    saveAddRoleData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.addFormData.createTime
          roleSave(this.addFormData, this.type).then(() => {
            this.addDialogFormVisible = false
            this.resetDataModel()
            this.getList()
            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    resetDataModel() {
      this.addFormData.name = ''
      this.addFormData.remark = ''
    },
    handleEdit(role){
      this.addFormData = Object.assign({}, role)
      this.addDialogFormVisible = true
      this.title = '编辑'
      this.type = true
    },
    handleRoleAuth(roleId) {
      this.roleId = roleId
      getRoleMenus({roleId: roleId}).then(response => {
        this.menuList = response.menuTree
        this.dialogFormVisible = true

        let menuIds = response.menuIds
        menuIds.forEach(val => {
          this.$nextTick(() => {
            this.$refs.tree.setChecked(val, true, false)
          })
        });
      }).catch(error => {
        console.log(error);
      })
    },
    saveData() {
      let idArray = this.$refs.tree.getHalfCheckedKeys().concat(this.$refs.tree.getCheckedKeys())
      let ids = idArray.toString()
      editRoleMenus({ids: ids, roleId: this.roleId}).then(response => { 
        this.dialogFormVisible = false
      }).catch(error => {
        console.log(error);
      })
    },
    getTreeLabel(data, node) {
      if (node.level == 1) {
        if (data.type == 1) {
          return data.name + ' - 总后台'
        } else {
          return data.name + ' - PC'
        }
      } else {
        return data.name + ' - ' + data.typeText
      }
    }
  }
}
</script>
